/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kimstore.gui.repair;

import com.kimstore.bean.Item;
import com.kimstore.bean.ItemStatus;
import com.kimstore.bean.RepairDetail;
import com.kimstore.bean.Staff;
import com.kimstore.factory.DaoFactory;
import com.kimstore.main.controller.RepairTabController;
import java.util.List;

/**
 *
 * @author Administrator
 */
public class AddItemForRepairController {

    private RepairTabController parentController;
    private AddItemForRepairWindow window;
    private Item selectedItem;

    public AddItemForRepairController(RepairTabController parentController) {
        this.parentController = parentController;

    }

    public void displayWindow() {
        window = new AddItemForRepairWindow(this);
        window.populateStaffs(DaoFactory.getInstance().getStaffDao().findAll());
        window.showWindow();
    }

    public void fromWindow(RepairDetail repair) {
        repair.setCurrentStatus(ItemStatus.IN_REPAIR);
        selectedItem.setRepairDetail(repair);

        // add repair item to database.
        DaoFactory.getInstance().getItemDao().saveOrUpdate(selectedItem);

        ItemStatus itemStatus = new ItemStatus(ItemStatus.IN_REPAIR, repair.getReceiveDate(), repair.getStaff());
        selectedItem.addHistory(itemStatus);
        DaoFactory.getInstance().getItemDao().saveOrUpdate(selectedItem);

        parentController.createAddItemToRepairControllerCallback(selectedItem);
    }

    public Staff getStaff(String staffName) {
        List<Staff> staffs = DaoFactory.getInstance().getStaffDao().findAll();

        for (Staff s : staffs) {
            if (s.getName().equals(staffName)) {
                return s;
            }
        }
        return null;
    }

    public void createNewSelectItemToRepairController() {
        SelectItemToRepairController controller = new SelectItemToRepairController(this);
        controller.displayWindow();
    }

    public void createNewSelectItemToRepairControllerCallback(Item item) {
        this.selectedItem = item;

        window.setItemSKU(item.getSerial());
        window.setProductName(item.getProduct().getName());
    }

    public void validate(RepairDetail repair) throws Error {
        if (selectedItem == null) {
            throw new Error("Please select an Item");
        }
        
        if(repair.getReceiveDate() == null)
                        throw new Error("Please indicate a date");


    }
}
